package com.gitee.security.validate;

import cn.hutool.core.util.StrUtil;
import com.gitee.security.handler.LoginFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired

    private LoginFailHandler loginFailHandler;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (StrUtil.equals(contextPath +"/login", request.getRequestURI()) && StrUtil.equalsIgnoreCase(request.getMethod(), "post")) {
            try {
                HttpSession session = request.getSession();
                Captcha captcha = (Captcha) session.getAttribute(CaptchaController.SESSION_KEY);
                String codeInRequest = request.getParameter("captcha");
                if (StrUtil.isBlank(codeInRequest)) {
                    throw new CaptchaException("验证码不能为空");
                }
                if (captcha == null || captcha.isExpired()) {
                    session.removeAttribute(CaptchaController.SESSION_KEY);
                    throw new CaptchaException("验证码已过期");
                }
                if (!StrUtil.equalsIgnoreCase(captcha.getCode(), codeInRequest)) {
                    throw new CaptchaException("验证码不匹配");
                }
                session.removeAttribute(CaptchaController.SESSION_KEY);
            } catch (CaptchaException e) {
                loginFailHandler.onAuthenticationFailure(request, response, e);
                return;
            }

        }
        filterChain.doFilter(request, response);
    }


}
